/**
 * 感谢小伙伴对中犇框架的杰出贡献
 * 从中涌现出很多优秀的组件
 * 此次大融合便于后期拆分进行
 * 为了便于JS请求所有请求采用/admin.php开头
 * 语言包暂时移除，如需支持多语言 可使用i18n支持
 * @author 晓风[215628355@qq.com] 
**/
//点击导出
	function btn_out(){
		$("input[name='export']").val('1');
		$("#manage_from").submit();
		return false;
	}
	//点击搜索
	function btn_out_search(){
		$("input[name='export']").val('0');
		$("#manage_from").submit();
		return false;
	}
	function clearinput() {
		$(".marBtm").find('input').val('');
		$(".marBtm").find(".select2").val('all').trigger('change');
		window.location.href = location.origin + location.pathname
	}
	var quickadd_href = "";
	$('.addCheck').click(function (e) {
		// console.log(e)
		var chk_value = [];
		$('input[name="ids[]"]:checked').each(function () {
			chk_value.push($(this).val());
		});
		$('input[name="ids"]').val(chk_value.join(','))
	});

	$('.layeradd').click(function (e) {
		// console.log(e)
		var chk_value = [];
		$('input[name="ids[]"]:checked').each(function () {
			chk_value.push($(this).val());
		});
		e.preventDefault()
		quickadd_href = $(this).attr('href');
		quickadd_href = quickadd_href + '?layer=1&ids=' + chk_value;
		opensidebar(quickadd_href)
		console.log(chk_value)
	});

	//批量发货单独使用
	$('.plfh').click(function (e) {
		var chk_value = [];
		$('input[name="ids[]"]:checked').each(function () {
			chk_value.push($(this).val());
		});
		if(chk_value.length == 0){
			layer.msg("请选择操作数据");
			return false;
		}
		e.preventDefault()
		quickadd_href = $(this).attr('href');
		quickadd_href = quickadd_href + '?layer=1&ids=' + chk_value;
		opensidebar(quickadd_href)
		console.log(chk_value)
	});

	$('.layeredit').click(function (e) {
		e.preventDefault()
		quickadd_href = $(this).attr('href');
		quickadd_href = quickadd_href + '?layer=1';
		opensidebar(quickadd_href)
	});

	function opensidebar(url) {
		console.log(url);
		layer.open({
			type: 2,
			title: false,
			closeBtn: true,
			shadeClose: true,
			scrollbar: true,
			offset: 'auto',
			anim: '7',
			area: ['60%', '90vh'],
			content: url
		})
	}

	$(".quickadd").click(function (e) {
		e.preventDefault()
		quickadd_href = $(this).attr('href');
		// var td = $('.table tbody tr:eq(0)').html();
		// var tr = '<tr>'+td+'</tr>'
		// $('.table tbody').prepend(tr);
		// var ttd = $('.table tbody tr:eq(0)').children()[2];

		var tablefields = $('#tablefields').val();
		var tablehide_checkbox = $('#tablehide_checkbox').val();

		//字符串转数组
		var fields = JSON.parse(tablefields)
		var html = '<tr>';
		if (!tablehide_checkbox) {
			html += '<td></td>';
		}

		for (var i = 0; i < fields.length; i++) {
			for (var j = 0; j < fields[i].length; j++) {

			}
			if (fields[i][0] == 'id') {
				html += '<td></td>';
			}

			else if (fields[i][0] == 'right_button') {
				html += '<td></td>';
			}

			else {
				if (fields[i][2] == 'text' || fields[i][2] == 'text.edit') {
					html += '<td><input type="text" name="" class="quickaddtext form-control input-sm" data-id="" data-name="' + fields[i][0] + '"  onblur="quickblur(this)"></td>';
				}
			}
		}
		html += '</tr>';
		$('.table tbody').prepend(html);

	})

	function quickblur(obj) {
		var txt = $(obj).val();
		var field = $(obj).attr('data-name');
		if (txt.length == 0) {
			return false;
		}
		var params = {};
		params[field] = txt;
		$.post(quickadd_href, params, function (data, status) {
			console.log(data)
			console.log(status)
			if (data.code == 1) {
				let newA = document.createElement('a')
				newA.setAttribute('href', 'javascript:void(0);')
				newA.setAttribute('class', 'text-edit editable editable-click')
				newA.setAttribute('data-placeholder', '请输入广告位名称')
				newA.setAttribute('data-table', 'c82f4b46')
				newA.setAttribute('data-type', 'text')
				newA.setAttribute('data-pk', '6')//使用添加成功的返回值
				newA.setAttribute('data-name', field)
				newA.innerText = txt
				console.log(newA)
				obj.parentElement.replaceChild(newA, obj)
			}
			else {
				layer.msg(data.msg);
			}
		});

	}

	$('#select-btn').click(function () {
		let myselect = document.querySelector('.select-mian');
		let index = myselect.selectedIndex;
		let val = myselect.options[index].value

		console.log(document.querySelector('.checkboxCtrl').getAttribute('data-group'))
		var chk_value = [];
		$('input[name="ids[]"]:checked').each(function () {
			chk_value.push($(this).val());
		});

		if (val == -1 || chk_value.length < 1) {
			layer.msg("请选择操作");
			return
		}
		var params = {
			'ids': chk_value,
			'action': $(".select-mian").find("option:selected").attr("action")
		};

		$.post(val, params, function (res) {
			console.log(res)
			if (res.code == 1) {
				layer.msg("操作成功");
				window.location.reload();
			} else {
				layer.msg("操作失败");
			}
		})
	})

	// 新增页面的选择链接
	function selectLink(callBack) {
		layer.open({
			title: "新增广告",
			type: 2,
			area: ['900px', '700px'],
			fixed: false, //不固定
			maxmin: true,
			content: "/admin.php/operation/ads/ad_layer",
			end: () => {
				let linkSrt = localStorage.getItem("myLink")
				callBack(linkSrt)
				localStorage.removeItem("myLink")
			}
		});
	}
    
    
    //BASE64转文件
    function dataURLtoFile(dataurl, filename) {//将base64转换为文件
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    }    
    
    /**
     * 通用图片裁切
     * 因裁剪复用代码过度，故进行拆解，此方法为基础功能实现
     * 将裁剪的base64字符串转为文件流上传并返回 ，可解决小带宽服务器无法上传问题
    **/
    function imageCov(data,callBack){
        localStorage.setItem('picSize', JSON.stringify(data.picSize));
        let picData = '';
		layer.open({
			title: "图片裁切",
			type: 2,
			area: ['950px', '600px'],
			fixed: false, //不固定
			maxmin: true,
			content: "/admin.php/operation/ads/cut",
			end: () => {
            	picData = localStorage.getItem('picBase64');
				localStorage.removeItem('picBase64')
                var file =  dataURLtoFile(picData,"裁剪图片.png");
                var formdata = new FormData();
                formdata.append('dir',"images");                
                formdata.append('file',file);
                $.ajax({
                    url:'/admin.php/admin/upload/save',  
                    type:'post',  
                    processData:false, 
                    contentType:false, 
                    data:formdata, 
                    success:function (res) { 
                        if (res.code == 1) {
                            callBack(res,picData);							
						}
                    }
                })
			}
		});
    }
    
    // 新增页面的图片裁切
	function addImgCov(data, callBack) {
        imageCov(data,function(res,picData){
            	data.picNum++;
                if (data.slideVal == '') {
                    data.slideVal += `${res.id}`;
                } else {
                    data.slideVal += `,${res.id}`;
                }

                data.Html.length = 0;
                data.Html.push(`<div id="WU_FILE_${data.picNum}" style="width:214px;" class="file-item js-gallery thumbnail">
                        <a data-magnify="gallery" id="iview" href="${res.path}">
                            <img src="${picData}" data-original="${res.path}"/>
                        </a>
                        <div class="info">xxxx</div>
                        <i class="fa fa-times-circle remove-picture" onclick="removePic(this)" data-id="${res.id}"></i>
                        <i class="fa fa-fw fa-arrows move-picture"></i>
                        <div class="file-state img-state">
                            <div class="bg-success">上传成功</div>
                        </div>
                    </div>`);

                let callData = {
                    Html: data.Html,
                    picNum: data.picNum,
                    slideVal: data.slideVal,
                    picData
                }
                callBack(callData);            
        })		
	}
	// 编辑页面的图片裁切
	function editImgCov(data, callBack) {
        imageCov(data,function(res,picData){
               data.picNum++;
                if (data.slideVal == '') {
                    data.slideVal += `${res.id}`;
                } else {
                    data.slideVal += `,${res.id}`;
                }

                // Html.push();

                let tempDom = `<div id="WU_FILE_${data.picNum}" style="width:214px;" class="file-item js-gallery thumbnail">
                    <a data-magnify="gallery" id="iview" href="${res.path}">
                        <img src="${picData}" data-original="${res.path}"/>
                    </a>
                    <div class="info">xxxx</div>
                    <i class="fa fa-times-circle remove-picture" onclick="removePic(this)" data-id="${res.id}"></i>
                    <div class="file-state img-state">
                        <div class="bg-success">上传成功</div>
                    </div>
                </div>`;

                let callData = {
                    picNum: data.picNum,
                    slideVal: data.slideVal,
                    picData,
                    tempDom
                }
                callBack(callData);
               //$("#file_list_images").html(tempDom)
        })	
    }
  
  
	// 文章列表页面新增功能的图片裁切 
	function essayAddImgCov(data, callBack) {
		addImgCov(data, callBack);
	}
	// 文章列表页面编辑功能的图片裁切 
	function essayEditImgCov(data, callBack) {
		editImgCov(data, callBack);
	}
  
  // 导航管理页面的新增选择链接 
	function navAddSelectLink(callBack , title) {
		let index = layer.open({
			title: title || "新增广告",
			type: 2,
			area: ['900px', '700px'],
			fixed: false, //不固定
			maxmin: true,
			content: "/admin.php/operation/ads/ad_layer",
			end: () => {
				let linkSrt = localStorage.getItem("myLink")
				callBack(linkSrt)
				localStorage.removeItem("myLink")
			}
		});
	}
	// 导航管理页面的编辑选择链接 
	function navEditSelectLink(callBack,title) {
         var title = title || "编辑广告";
		 navAddSelectLink(callBack,title);
	}
    
    function add_quick(menu_id){
            $.get('/admin.php/admin/index/quick_menu'+'?menuid='+menu_id, function(res){
                if (res.code) {
                    layer.msg(res.msg);
                }else{
                    layer.msg(res.msg,function(){});
                }
           })
    }

    function del_quick(menu_id){
        $.get('/admin.php/admin/index/quick_menu_del'+'?menuid='+menu_id, function(res){
            if (res.code) {
                layer.msg(res.msg);
                $('#menu-10-'+menu_id).remove();
            }else{
                layer.msg(res.msg,function(){});
            }
        })
    }
    
    function childMenu(id,jsonarr)
    {
        // 处理侧栏样式
        // $(".child2").removeClass("active");
        // $(this).addClass("active");
        console.log()
        // 处理数据 
        let html = '';
        let url = '';
        $.each(jsonarr,function(key,submenu){ 
            let num = 0;
            // <div class="son_title {$menu['id'] == $location[1]["id"]?='active'}">{$menu.title}</div>

            if(submenu.id == id){
                $.each(submenu.child,function(childKey,childSubmenu){
                    num++;
                    let str;

                    if(submenu.id == 10){
                        str = `<span class="quick_icon pull-right" onclick="del_quick(${childSubmenu.id})" title="删除快捷菜单">×</span>`;
                    }else{
                        str = `<span class="quick_icon pull-right" onclick="add_quick(${childSubmenu.id})" title="添加快捷菜单">+</span>`;
                    }
                    html += `
                        <li id="menu-${submenu.id}-${childSubmenu.id}" class="treeview child2 ${num == 1?'active':''}" style="list-style-type:none;">
                            <a href="${childSubmenu.url_value}" target="${childSubmenu.url_target}" >${childSubmenu.title}</a >
                            ${str}   
                        </li>
                    `
                    if(num == 1){
                        url = childSubmenu.url_value;
                    }
                });
            }
        });
        let html1 = `<ul class="left_menu_content_ul"><li class="treeview" ><ul>${html}</ul></li></ul>`;
        $('#childBuilder').html(html1);
        window.location.href = url;
     }
    
     function menuHide(id){
        console.log(id);
        $('.glyphicon').removeClass('glyphicon-menu-down');
        $('.glyphicon').removeClass('glyphicon-menu-up');
        $('.glyphicon').addClass('glyphicon-menu-down');
        // $('#men_'+id).removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up')
        let flag =false ;
        if( $('#sub_'+id).is(":hidden")){
            flag = false
        }else{
            flag = true
        }
        $('.child-menu').hide();
        if(flag){
            $('#sub_'+id).hide();
        }else{
            $('#sub_'+id).show();
            $('#men_'+id).removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up')
        }
    }
    
      // 删除图片
    function removePic(ele) {
        let tempId = ele.getAttribute("data-id");
        slideVal = slideVal.replace(tempId,'');
        $('#img_url').attr({ 'value': slideVal });
    }
    function findinput() {
		var focusinput = $(":focus").focus();
		var nextinput = $(focusinput).parent().parent().nextAll().find("input[type='text']");
		if (nextinput.length > 0) {
			nextinput[0].focus();
		}
	}

	function closelayer() {
		var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
		parent.layer.close(index);
	}
    
(function(){    
        let Html; // 空的模板字符串
        let slideVal = ''; // 此属性是图片裁剪完之后给from表单的input的value赋值的,不可删除
        let picNum = 0; // 上传的图片数量     
        setInterval(function(){
            $.ajax({
                type: 'POST',
                url: '/admin.php/order/order/new_order',
                success: (res) => {
                    if(res.code==1 && res.data && res.data.order_sn){
                     //  //边缘弹出
                     layer.open({
                        type: 1,
                        title:"订单提醒",
                        time: 4000, //20s后自动关闭
                        offset: 'rt' //具体配置参考：offset参数项
                        ,content: '<div style="padding: 20px 80px;">'+"{:lang('您好你有个新的订单，订单号')}"+'：'+ res.data.order_sn +'</div>'
                        ,btn: "关闭全部"
                        ,btnAlign: 't' //按钮居中
                        ,shade: 0 //不显示遮罩
                        ,yes: function(){
                            console.log('yes',4444)
                            layer.closeAll();
                        },
                        end:function(){
                            console.log('end',4414)
                        },

                        });

                 
                    }
                }
            })

        },5000)
         // 切换多语言
        $('#cont').change(function() {
            let val = $(this).val();
            let url=window.location.href;

            $.ajax({
                data:{
                    language:val,
                },
                    type: 'POST',
                    url: '/admin.php/user/index/lang',
                    success: (res) => {
                        window.location.href=url;
                    }
                })
        })
        // 新增页面（需要在用到这个功能的页面添加一个layer弹窗）
        $('#addimgcutUploadPic').on('click', async () => {
            let cutPicWidth = 0; // 裁剪图片的宽度
            let cutPicHeight = 0; // 裁剪图片的高度
            console.log('我被请求啦',window.location.href)
            // 在这里修改裁剪图片的大小
            await new Promise((resolve, reject) => {
                $.post('/admin.php/operation/ads_type/getSize', { "id": $("#category_id").val() })
                .then(res => {
                    if (res.code == 1) {
                        cutPicWidth = res && res.data && res.data.width || 400;
                        cutPicHeight = res && res.data && res.data.height || 400;
                        resolve();
                    }
                });
            });
            let picSize = {
                "width": 400,
                "height": 400
            };
            localStorage.setItem('picSize', JSON.stringify(picSize));
            // 调用父级页面的方法的参数
            slideVal = $('#img_url').attr('value')
            let data = {
                slideVal,
                picNum,
                Html,
                picSize
            }
            parent.window.essayAddImgCov(data,(callData) => {
                
                slideVal = callData.slideVal;
                picNum = callData.picNum;
                Html = callData.Html;
                $('#img_url').attr({ 'value': callData.slideVal });
                $("#file_list_addimgcut").append(callData.Html);
            })
        })
})
    